<script setup>
import { ref, getCurrentInstance, onMounted, defineProps, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';

// 使用 ref 来创建响应式变量
let recommend = ref([]);
let total = ref(0);

// 获取 props 来传递父组件的 userId, 管理状态以及书单数据
const props = defineProps({
  userId: {
    type: [String, Number],
    required: false,
  },
  isManagingrecommend: {
    type: Boolean,
    default: false,
  },
  recommendFromParent: {
    type: Array,
    default: null,
  },
});

const { proxy } = getCurrentInstance();

// 使用父组件传入的博客数据时更新
watch(
  () => props.recommendFromParent,
  (newrecommend) => {
    if (newrecommend) {
      recommend.value = newrecommend;
      total.value = recommend.value.length;
    }
  },
  { immediate: true }
);

// 获取博客的总数量
const getLength = async () => {
  try {
    const response = await proxy.$axios.get('/recommend');
    console.log("getLength Response:", response.data); // 打印返回的内容
    return response.data.data; // 确保返回的是长度，而不是数据本身
  } catch (error) {
    console.error('Error fetching data:', error);
    return 0; // 如果失败，返回 0 作为默认值
  }
};

// 根据页码获取博客数据
const getbook = async (page) => {
  try {
    let url = props.userId ? `/recommend/user/${props.userId}` : `/recommends/${page}`;
    const response = await proxy.$axios.get(url);
    console.log("Response Data:", response.data); // 查看后端返回的数据
    recommend.value = response.data.data;
    if (props.userId) {
      total.value = recommend.value.length;
    } else {
      total.value = await getLength();
    }
    console.log("Total:", total.value); // 确保在设置 total 之后打印
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 刷新数据专用
const reflash = async (page) => {
  try {
    let url =`/recommends/${page}`;
    const response = await proxy.$axios.get(url);
    recommend.value = response.data.data;
      total.value = await getLength();
    console.log("Total:", total.value); // 确保在设置 total 之后打印
    isManagingrecommend.value = false
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 删除书单
const deletebook = async (bookId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个书单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await proxy.$axios.delete(`/recommend/${bookId}`);
    ElMessage.success('删除成功');
    getbook(1); // 删除之后刷新数据
  } catch (error) {
    console.error('Error deleting book:', error);
    ElMessage.error('删除失败');
  }
};

// 使用 onMounted 来获取数据，如果没有从父组件传递博客数据
onMounted(() => {
  getbook(1);
  getLength;
});

// 当 userId 改变时，重新加载博客
watch(
  () => props.userId,
  (newUserId) => {
    if (newUserId) {
      getbook(1);
    }
  }
);

// 定义函数来处理卡片点击
const handleCardClick = async (book) => {
  try {
    const add_view = await proxy.$axios.get(`/recommend_add/${book.id}`);
    proxy.$emit('navigateToRecomments', book);
  } catch (error) {
    console.error("Failed to add view:", error);
  }
};


// 编辑博客
const editbook = (bookId) => {
  proxy.$emit('editbook', bookId);
};
</script>
<template>
  <div class="recommend-container">
    <div class="main">
      <el-row :gutter="20">
        <el-col
          v-for="(book) in recommend"
          :key="book.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="8"
        >
          <el-card
            shadow="hover"
            class="book-card"
            @click="handleCardClick(book)"
          >
            <div class="book-image">
              <img
                :src="book.img_url"
                alt="书单图片"
                class="book-img"
              />
            </div>
            <div class="book-info">
              <h3 class="book-title">{{ book.title }}</h3>
              <p class="book-content">{{ book.content }}</p>
              <p class="book-rating">
                评分：
                <el-rate
                  v-model="book.star"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </p>
              <p class="book-views">
                阅读：<i class="el-icon-view"></i>{{ book.view_sum }}
              </p>
            <div class="book-actions" v-if="props.isManagingrecommend">
              <el-button type="danger" @click="deletebook(book.id)">删除</el-button>
              <el-button type="primary" @click="editbook(book.id)">编辑</el-button>
            </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="footer">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="6"
        @current-change="getbook"
      />
    </div>

    <!-- 返回按钮 -->
    <div class="back-to-list">
      <el-button @click="$emit('navigateTorecommend')">返回书单列表</el-button>
      <el-button @click="getbook(1), getLength()">刷新书单列表</el-button>
    </div>
  </div>
</template>

<style scoped>
.recommend-container {
  padding: 20px;
  background: #f7f7f7;
  border-radius: 8px;
  max-width: 1200px;
  margin: 0 auto;
}

.main {
  margin-bottom: 30px;
}

.book-card {
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.book-image {
  text-align: center;
  margin-bottom: 10px;
}

.book-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.book-info {
  padding: 10px;
}

.book-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.book-content {
  font-size: 14px;
  color: #666;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-rating,
.book-views {
  font-size: 14px;
  color: #999;
}

.footer {
  margin-top: 20px;
  text-align: center;
}

.back-to-list {
  margin-top: 20px;
  text-align: center;
}
</style>
